package com.sa.app.activities;

import java.util.ArrayList;
import java.util.List;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;

import com.sa.app.R;
import com.sa.app.fragments.DatasheetFragment;
import com.sa.app.fragments.ItemFragment;
import com.sa.app.fragments.RealServiceFragment;
import com.sa.app.fragments.RegionFragment;
import com.sa.app.fragments.VirtualServiceFragment;
import com.sa.app.objects.DatasheetLine;
import com.sa.app.objects.Item;
import com.sa.app.objects.ItemImpl;
import com.sa.app.objects.Region;
import com.sa.app.objects.RegionImpl;
import com.sa.app.utilities.DataBaseManager;
import com.sa.app.utilities.MyApplication;


public class ItemActivity extends FragmentActivity implements ActionBar.TabListener {
	/** Called when the activity is first created. */

	private Item itemActual;
	private DataBaseManager dataBaseManager;
	private List<DatasheetLine> datasheets;
	private Location location;
	
	private SectionsPagerAdapter mSectionsPagerAdapter;
	private ViewPager mViewPager;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_item);
		initializeTabs();
		getActionBar().setHomeButtonEnabled(true);
		Intent intent = getIntent();
		// Vengo de ItemsFragment(MainActivity)
		
		if (intent.getAction().equals("ItemsFragment") || intent.getAction().equals("ServiceActivity")) {

			String[] s = intent.getStringArrayExtra("item");
			MyApplication ma = (MyApplication) getApplicationContext();
			dataBaseManager = ma.getDataBase();
			location = ma.getLocation();

			List<String> l = dataBaseManager.selectItemByNFCID(s[0]).get(0);

			Integer regionLatitude = Integer.valueOf((l.get(7)));
			Integer regionLongitude = Integer.valueOf((l.get(8)));			
			List<List<String>> queryResult = new ArrayList<List<String>>();
			String query = "SELECT * FROM regions WHERE latitude='" + regionLatitude
					+ "' AND longitude='" + regionLongitude + "'";
			queryResult = dataBaseManager.query(query);
			List<String> regionList = queryResult.get(0);
			Region region = new RegionImpl(regionList.get(0), Integer.valueOf(regionList
					.get(1)), Integer.valueOf(regionList.get(2)), Integer.valueOf(regionList.get(3)));

			itemActual = new ItemImpl(l.get(0), l.get(1), l.get(2), l.get(3), l.get(4), l.get(5), l.get(6), region,
					dataBaseManager.generateVirtualServicesList(l.get(0)),dataBaseManager.generateRealServicesList(l.get(0)),dataBaseManager.generateDatasheetList(l.get(0)));

			//initializeTabs();
			datasheets=dataBaseManager.generateDatasheetList(itemActual.getNfcID());
			
		} else  {

			//LANZAR ERROR
		}

	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.item_activity, menu);
		return true;
	}

	@Override
	/** Needed to keep config between orientation changes ***/
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	public DataBaseManager getDataBaseManager() {
		return dataBaseManager;
	}

	public Location getLocation() {
		return location;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.label) {
			asignAlias();
		} else if (item.getItemId() == R.id.delete) {
			deleteItem();
		}else if (item.getItemId() == android.R.id.home) {
			Intent i = new Intent(getApplicationContext(), MainActivity.class);
			i.setAction("ItemActivity");
			startActivity(i);
		}
		return false;
	}

	private void initializeTabs(){
		// Create the adapter that will return a fragment for each of the three primary sections
		// of the app.
	
		mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

		// Set up the action bar.
		final ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager2);
		mViewPager.setAdapter(mSectionsPagerAdapter);

		// When swiping between different sections, select the corresponding tab.
		// We can also use ActionBar.Tab#select() to do this if we have a reference to the
		// Tab.
		mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				actionBar.setSelectedNavigationItem(position);
			}
		});
	
		// For each of the sections in the app, add a tab to the action bar.
		for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
			// Create a tab with text corresponding to the page title defined by the adapter.
			// Also specify this Activity object, which implements the TabListener interface, as the
			// listener for when this tab is selected.
			actionBar.addTab(
					actionBar.newTab()
					.setText(mSectionsPagerAdapter.getPageTitle(i))
					.setTabListener(this));
		}
		mViewPager.setCurrentItem(1);
	}
	
	@Override
	public void onResume() {
		super.onResume();

	}
	
	@Override
	public void onPause() {
		super.onPause();
	
	}

	

	
	public void asignAlias() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this).setTitle(
				getString(R.string.enter_alias)).setMessage(
						getString(R.string.asign_alias));

		final EditText input = new EditText(this);
		builder.setView(input);

		builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				
				String newAlias = input.getText().toString();
				if(!newAlias.equals("") && getDataBaseManager().selectItemByAliasID(newAlias).isEmpty()){
				
				String s = "UPDATE items SET aliasID='"+newAlias+"' WHERE NFCID='"+itemActual.getNfcID()+"'";
				getDataBaseManager().query(s);
				}else{
					Toast.makeText(getApplicationContext(), getString(R.string.invalid_alias), Toast.LENGTH_LONG).show();
				}
			}
		});
		builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Canceled.
			}
		});
		builder.show();
	}

	public void deleteItem() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this).setTitle(
				getString(R.string.delete_item)).setMessage(
						getString(R.string.information_lost));

		builder.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {


				List<String> region=getDataBaseManager().getItemLastRegion(itemActual.getNfcID());
				getDataBaseManager().deleteItem(itemActual.getNfcID());

				//TODO meto aqui la consulta por no modificar metodos que ya estan en la documentación. Nombre metodo: isErasable()
				String sql= "SELECT * FROM regions, items WHERE regionLatitude=latitude AND regionLongitude=longitude AND regionLatitude="+region.get(1)+" AND regionLongitude="+region.get(2);
				if(getDataBaseManager().query(sql).isEmpty()){
					//TODO meto aqui la consulta por no modificar metodos que ya estan en la documentación. Nombre metodo: deleteRegion()

					String q= "DELETE FROM regions WHERE latitude="+region.get(1)+" AND longitude="+region.get(2);
					getDataBaseManager().execSQL(q);

				}



				Intent i = new Intent(getApplicationContext(), MainActivity.class);
				i.setAction("ItemActivity");
				startActivity(i);
			}
		});
		builder.setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Canceled.
			}
		});
		builder.show();
	}

	public Item getItemActual() {
		return itemActual;
	}

	public List<DatasheetLine> getDatasheets() {
		return datasheets;
	}

	/**
	 * This is the private class used by the ActionBar in order to link a tab
	 * with its fragment content.
	 */

	
	public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {
		
		
	}
	
	public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
		
        mViewPager.setCurrentItem(tab.getPosition());
		
	}
	
	public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
		
		
	}

	/**
	 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
	 * sections of the app.
	 */
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int i) {
			Fragment fragment=null;
			if(i==0){
				fragment = new VirtualServiceFragment();
			}else if(i==1){
				fragment = new ItemFragment();
			}else if(i==2){
				fragment= new RealServiceFragment();
			}else if(i==3){
				fragment=new RegionFragment(); 
				//fragment= new VirtualServiceFragment();
			}else if(i==4){
				fragment= new DatasheetFragment();
			}
			
			
	
			return fragment;
		}

		@Override
		public int getCount() {
			return 5;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			switch (position) {
			case 0: return getString(R.string.virtual_service).toUpperCase();
			case 1: return getString(R.string.item).toUpperCase();
			case 2: return getString(R.string.real_service).toUpperCase();
			case 3: return getString(R.string.location).toUpperCase();
			case 4: return getString(R.string.datasheet).toUpperCase();
			
			}
			return null;
		}
	}


}
